﻿using DongFangGuoKai.WMSPlatform.WebApi.Collection;
using DongFangGuoKai.WMSPlatform.WebApi.Protobuf;
using Newtonsoft.Json;
using StackExchange.Redis;
using System.Net.WebSockets;
using System.Text;

namespace DongFangGuoKai.WMSPlatform.WebApi.BackgroundTakss
{
    public class RedisSubBackgroundService : BackgroundService
    {
        private static readonly List<string> subChannels = new List<string>()
        {
                 "RCS_ROBOT_123ABCD01AB01AB_XY",
                 "RCS_ROBOT_123ABCD01AB01AB_AA"
        };
        private static readonly Action< ChannelMessage> action = m =>
        {
            byte[] protobufBytes = (byte[])m.Message; // 你的Protobuf数据
            var protobufData = data.Parser.ParseFrom(protobufBytes);

            var result = JsonConvert.SerializeObject(protobufData);

            Console.WriteLine(result);

            WebSocketCollection.GetAllSocketClients()?.ForEach(async socket =>
            {

                await socket.WebSocket.SendAsync(Encoding.UTF8.GetBytes(result), WebSocketMessageType.Text, true, CancellationToken.None);

            });


        };
        private static readonly ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect("10.10.20.180:9736,password=Hik@1234");

        private readonly ILogger<RedisSubBackgroundService> logger;

        public RedisSubBackgroundService(ILogger<RedisSubBackgroundService> logger)
        {
            this.logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {

                Console.WriteLine($"Redis连接状态：{connectionMultiplexer.IsConnected}");
                //获取订阅者实例
                var sub = connectionMultiplexer.GetSubscriber();

                subChannels?.ForEach(channel =>
                {
                    Console.WriteLine($"-------{channel}开始订阅-------------------------");
                    //订阅话题
                    var channelMesaageQuece = sub.Subscribe(channel);
                    channelMesaageQuece.OnMessage(action);
                });

            }
            catch (Exception ex)
            {

                logger.LogError(ex.Message);
            }



        }


    }
}
